package com.education.ai.controller;

import com.education.ai.service.ExerciseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * AI对话控制器
 */
@RestController
@Slf4j
public class ChatController {

    @Autowired
    @Qualifier("qwenWebClient")
    private WebClient qwenWebClient;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private ExerciseService exerciseService;
    
    @Value("${qwen.model:qwen-max}")
    private String model;

    /**
     * AI对话接口
     */
    @PostMapping("/api/chat")
    public ResponseEntity<Map<String, Object>> chat(@RequestBody Map<String, Object> requestBody) {
        try {
            String message = (String) requestBody.get("message");
            Map<String, Object> context = (Map<String, Object>) requestBody.get("context");
            
            if (message == null || message.trim().isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "消息不能为空");
                errorResponse.put("data", null);
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            log.info("收到AI对话请求: {}, 上下文: {}", message, context);
            
            // 构建提示词
            String prompt = buildPrompt(message, context);
            
            // 构建API请求
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("model", model);
            requestData.put("prompt", prompt);
            requestData.put("result_format", "text"); // 对话功能使用文本格式返回
            
            log.debug("发送到API的请求: {}", requestData);
            
            // 调用通义千问API
            String responseJson = qwenWebClient.post()
                .bodyValue(requestData)
                .retrieve()
                .bodyToMono(String.class)
                .block();
            
            log.debug("AI应答: {}", responseJson);
            
            // 解析API响应
            String aiReply = extractReplyFromResponse(responseJson);
            
            // 构建响应
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("reply", aiReply);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", responseData);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("AI对话失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "AI对话失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 构建提示词
     */
    private String buildPrompt(String message, Map<String, Object> context) {
        StringBuilder promptBuilder = new StringBuilder();
        
        // 添加角色设定
        promptBuilder.append("你是一位专业的教育AI助手，专注于帮助教师准备教案和习题。\n\n");
        
        // 添加上下文信息
        if (context != null) {
            String stage = (String) context.get("stage");
            String subject = (String) context.get("subject");
            String textbook = (String) context.get("textbook");
            String chapter = (String) context.get("chapter");
            
            if (stage != null) promptBuilder.append("学习阶段: ").append(stage).append("\n");
            if (subject != null) promptBuilder.append("学科: ").append(subject).append("\n");
            if (textbook != null) promptBuilder.append("教材: ").append(textbook).append("\n");
            if (chapter != null) promptBuilder.append("章节: ").append(chapter).append("\n");
            
            promptBuilder.append("\n");
        }
        
        // 添加用户消息
        promptBuilder.append("用户问题: ").append(message).append("\n\n");
        
        // 添加指导
        promptBuilder.append("请根据上述信息，提供专业、有针对性的教育建议或回答。");
        
        return promptBuilder.toString();
    }
    
    /**
     * 从API响应中提取回复内容
     */
    private String extractReplyFromResponse(String responseJson) {
        try {
            Map<String, Object> response = objectMapper.readValue(responseJson, Map.class);
            Map<String, Object> output = (Map<String, Object>) response.get("output");
            
            if (output != null && output.containsKey("text")) {
                return (String) output.get("text");
            } else {
                log.error("无法从响应中提取回复: {}", responseJson);
                return "抱歉，AI助手暂时无法提供有效回复。";
            }
        } catch (Exception e) {
            log.error("解析AI响应失败", e);
            return "抱歉，解析AI回复时发生错误。";
        }
    }
} 